#!/usr/bin/env bash

set -euo pipefail

usage() {
  cat <<'EOF'
Usage: linux_transport_watch.sh <endpoint> [interval_seconds] [--format table|json]

Continuously polls FIFO health information via asycipcctl and prints the
timestamped output. Defaults to table format every 10 seconds.

Environment variables:
  ASYIPCCTL_BIN   Override path to asycipcctl binary.
  ASYIPC_RUNTIME_DIR  Override runtime directory resolution for the CLI.
EOF
}

UNAME="$(uname -s)"
if [[ "${UNAME}" != "Linux" && "${UNAME}" != "Darwin" ]]; then
  echo "linux_transport_watch.sh is intended for Linux or macOS hosts" >&2
  exit 0
fi

if [[ $# -lt 1 ]]; then
  usage
  exit 1
fi

ENDPOINT=$1
INTERVAL=${2:-10}
shift
if [[ $# -gt 0 ]]; then
  shift
  FORMAT_ARG="$1"
else
  FORMAT_ARG="table"
fi

CLI_BIN=${ASYIPCCTL_BIN:-"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/build/asycipcctl"}

if [[ ! -x "${CLI_BIN}" ]]; then
  echo "asycipcctl binary not found: ${CLI_BIN}" >&2
  echo "Build it first: cmake --build build --target asycipcctl" >&2
  exit 1
fi

if ! [[ ${INTERVAL} =~ ^[0-9]+$ ]]; then
  echo "invalid interval: ${INTERVAL}" >&2
  exit 1
fi

poll() {
  local timestamp
  timestamp="$(date --iso-8601=seconds)"
  echo "==== ${timestamp} ===="
  "${CLI_BIN}" sessions list "${ENDPOINT}" --format "${FORMAT_ARG}" || true
  echo
}

while true; do
  poll
  sleep "${INTERVAL}"
done
